#!/usr/bin/python
"""Simple wrapper to automatically upload missing users to choosegame

This is a temporary solution that allows us to workaround the auto-fetching
code within the application not actually being done yet. Expect this to be
removed in the future, unless there's a reason to move the fetching part
away from the core application.

"""

import getopt
import os
import httplib
import subprocess
import sys
import urllib

# Access URLs for the live and development versions of the server.
# TODO: move this out into a config file somewhere.
dev_url = "http://localhost:8080"
live_url = "http://choosegame.appspot.com"

def GetMissing(app_url):
  "Returns a list of the missing people"
  url_path = "/data/missing"

  openurl = urllib.urlopen(app_url + url_path)
  data = openurl.read()

  namelist = data.split("\n")
  missing_names = []
  for name in namelist:
    name = name.strip()
    if name:
      missing_names.append(name)

  return missing_names

def FetchOneUser(user, dev=False):
  "Initiate a single fetch using the external tool"

  fetch_app = "./upload_games.py"
  args = ["--chunk"]
  if dev:
    args.append("--dev")
  args.append(user)

  subprocess.call([fetch_app] + args)

def Usage():
  print "Usage: auto_upload [ OPTIONS ]"
  print "options:"
  print "  --dev             Use local dev instance"

def main(argv):
  try:
    (opts, argv) = getopt.getopt(argv, "", [ "dev" ])
  except getopt.GetoptError:
    Usage()
    sys.exit(2)

  opts = dict(opts)
  if "--dev" in opts:
    instance = dev_url
    dev = True
  else:
    instance = live_url
    dev = False

  missing_list = GetMissing(instance)

  if missing_list:
    print "Found missing users:", missing_list
    for user in missing_list:
      FetchOneUser(user, dev=dev)

if __name__ == "__main__":
  main(sys.argv[1:])
